import { defineStore } from 'pinia';

export const useWorkflowStore = defineStore('workflow', {
  state: () => ({
    workflowData: null, // GoJS模型数据
    currentNodeId: null, // 当前选中需要配置参数的节点ID
    isParamConfigVisible: false,
    // 添加节点状态管理
    nodeStates: {}, // 存储节点状态
    executionResults: {}, // 存储执行结果
  }),
  getters: {
    currentNode(state) {
      if (!state.currentNodeId || !state.workflowData || !state.workflowData.nodeDataArray) return null;
      return state.workflowData.nodeDataArray.find(n => n.key === state.currentNodeId);
    },
    currentNodeParams(state) {
        const node = this.currentNode;
        return node ? (node.params || {}) : {};
    },
    // 添加获取节点状态的getter
    getNodeState: (state) => (nodeId) => {
      return state.nodeStates[nodeId] || 'pending';
    }
  },
  actions: {
    updateWorkflow(data) {
      this.workflowData = data;
    },
    setWorkflow(data) {
      this.workflowData = data;
    },
    openParamConfig(nodeId) {
      this.currentNodeId = nodeId;
      this.isParamConfigVisible = true;
    },
    closeParamConfig() {
      this.isParamConfigVisible = false;
      this.currentNodeId = null;
    },
    saveNodeParams(params) {
      if (this.currentNode) {
        // Pinia状态是响应式的，但GoJS model不是，所以这里需要一种方式通知GoJS更新
        // 一种方法是直接在GoJS的事件监听中处理，或者在这里发出事件
        // 这里我们只更新store，GoJS的更新在Canvas组件中处理
        const node = this.workflowData.nodeDataArray.find(n => n.key === this.currentNodeId);
        if (node) {
            node.params = { ...node.params, ...params };
        }
        this.closeParamConfig();
      }
    },
    // 添加节点状态管理方法
    updateNodeState(nodeId, status) {
      this.nodeStates[nodeId] = status;
    },
    setExecutionResult(nodeId, result) {
      this.executionResults[nodeId] = result;
    },
    startExecution() {
      // 重置所有节点状态
      this.nodeStates = {};
      this.executionResults = {};
      if (this.workflowData && this.workflowData.nodeDataArray) {
        this.workflowData.nodeDataArray.forEach(node => {
          this.nodeStates[node.key] = 'pending';
        });
      }
    },
    finishExecution() {
      // 执行完成后的处理
    }
  },
});